    export default {
        name: "bgsxtable",
        setup(props, { emit }) {
            const router = VueRouter.useRouter();
            const route = VueRouter.useRoute();
            const { smartSpeak } = inject('speech') || { smartSpeak: () => {} }; //语音
            const id = ref(route.query.id);
            const ids = ref([]);
            const bgsx = ref({});
            const tableData = ref([]);
            const search = ref('');
            const tables = ref();
            const jsonkeys = ref(['muselect', 'checkbox', 'multiimage', 'subtable', 'multifile', 'video', 'area']);
            const zdoptions = ref([]); //字段下拉选项
            const dialogBgsx = ref(false);
            const showFilterForm = ref(false);//筛选
            const plczdialog = ref(false); //单列筛选
            const plcxdata = ref({key: '', value: ''});//单列筛选输入值
            const filterForm = ref({});
            const selectrows = ref([]); //选择行数据
            const filterzzf =ref(null);
            const allusers = ref([]); //全部用户列表用于显示填报人
            const user = JSON.parse(localStorage.getItem('user')) || {};
            const activityType = ref([]); //显示和隐藏列
            const printzzj = ref(null);
        	// 证书表单数据
        	const zdformData = reactive({
        		id: null,
        		ids: [],
        		overwrite: true,
        		name_field: '',
        		storage_key: '',
        	})
        
        	// Word表单数据
        	const wordformData = reactive({
        		id: 0,
        		overwrite: '否',
        		field: '',
        		wjm: '',
        		ids: [],
        	})
        	const showZSPopup = ref(false)
        	const showWordPopup = ref(false)
			const pagination = ref({
                page: 1,
                size: 15,
                total: 0,
                sizes: [10, 20, 50, 100],
                layout: 'total, sizes, prev, pager, next, jumper'
            });
            const sortParams = ref({field: '',order: '', sortType: ''}); //排序
            const columns = ref([]);
            const zds = ref({});
            const fields = ref([]);
            const api = {
                create: addtablerow,
                update: updatetablerow,
                delete: deltablerow
            }

            onMounted(() => {
                if(id.value) getbgsx();
            });
            
            const isadmin = computed(() => {
                return ['admin', 'xmgly'].includes(user.Role);
            })
            
			const gettbyuser = async () => {
			    const res = await getformusers();
			    if(res) {
                    allusers.value = res.map(user => ({ label: user.name, value: user.id }));
			    }
			}
            
            const iszs = computed(()=>{
				if (!bgsx.value || !bgsx.value.fields) {
					return false;
				}
				const fieldsArray = Array.isArray(bgsx.value.fields) ? bgsx.value.fields : Object.values(bgsx.value.fields);
				return !!fieldsArray.find(e => e.type === 'sczs');
            });
            
            const isword = computed(()=>{
				if (!bgsx.value || !bgsx.value.fields) {
					return false;
				}
				const fieldsArray = Array.isArray(bgsx.value.fields) ? bgsx.value.fields : Object.values(bgsx.value.fields);
				return !!fieldsArray.find(e => e.type === 'word');
            });
            
			const getbgsx = async() => {
			    await gettbyuser();
				await getbgsxapi({id: Number(id.value)}).then(res => {
					bgsx.value = res || {};
					if (bgsx.value.fields) {
						zdformData.id = res.id;
						processFieldOptions();
						getData();
					}
				});
			};
			
			//过滤不能做文件名的字段，获取其他字段下拉选项，以及处理表头和字段，以及options选项
            const processFieldOptions = () => {
                const nofields = new Set([...jsonkeys.value, 'image', 'word']);
                const myfields = bgsx.value.fields;
                // 处理字段选项逻辑
                const splitPathToOptions = path => path.split('/').map(v => ({ value: v, label: v }));
                // 处理原始业务字段（排除系统字段）
                const processFields = fields => Object.entries(fields).flatMap(([key, field]) => {
                    const systemFields = ['is_locked', 'query_count'];
                    return !field || systemFields.includes(key) ? [] : [{
                        prop: key,
                        label: field.name,
                        width: field.width || undefined,
                        ...field
                    }];
                });
                // 处理字段类型和选项
                Object.entries(myfields).forEach(([key, field]) => {
                    zds.value[key] = field.name;
                    if (['select', 'muselect', 'radio', 'checkbox'].includes(field.type) && field.options) {
                        field.options = splitPathToOptions(field.options);
                    }
                });
                // 初始化各列分类
                const businessColumns = processFields(myfields); // 业务字段
                const systemColumns = [ // 系统字段
                    { type: 'query_count', prop: 'query_count', label: '查询次数', width: 100 },
                    { type: 'is_locked', prop: 'is_locked', label: '锁定状态', width: 100 }
                ];
                const reservationConfig = { // 预约字段配置
                    columns: [
                        { prop: 'reservation_date', label: '预约日期', type: 'date' },
                        { prop: 'slot_start', label: '开始时间', type: 'time' },
                        { prop: 'slot_end', label: '结束时间', type: 'time' },
                        { prop: 'sequence_number', label: '排号', type: 'number' }
                    ],
                    zdsEntries: {reservation_date: '预约日期', slot_start: '开始时间', slot_end: '结束时间',sequence_number: '排号'}
                };
                // 构建最终列顺序：业务 → 预约 → 系统
                columns.value = [
                    ...businessColumns,
                    ...(bgsx.value.isReservation ? reservationConfig.columns : []),
                    ...systemColumns
                ];
                // 处理表单字段
                fields.value = processFields(myfields);
                if (bgsx.value.isReservation) {
                    zds.value = { ...zds.value, ...reservationConfig.zdsEntries };
                    fields.value.push(
                        { prop: 'reservation_date', label: '预约日期', type: 'date' },
                        { prop: 'slot_start', label: '开始时间', type: 'time'},
                        { prop: 'slot_end', label: '结束时间', type: 'time'},
                        { prop: 'sequence_number', label: '排号', type: 'number'}
                    );
                }
                // 初始化其他配置
                zdoptions.value = mapAndFilterFields(field => !nofields.has(field.type));
                if (activityType.value.length === 0) {
                    // 调整活动类型字段顺序
                    const baseFields = [
                        ...Object.keys(myfields),
                        ...(bgsx.value.isReservation ? reservationConfig.columns.map(c => c.prop) : [])
                    ];
                    activityType.value = [...baseFields,'query_count', 'is_locked', 'cjz', 'created_at', 'updated_at'];
                    zds.value = {...zds.value,query_count: '查询次数',is_locked: '锁定',cjz: '填报人',created_at: '创建时间',updated_at: '更新时间'};
                }
            };
			
			// 生成下拉选项
            const mapAndFilterFields = (predicate) => {
				const fields = bgsx.value.fields;
				return Object.keys(fields).map(fieldKey => {
					const field = fields[fieldKey];
					if (predicate(field)) {
						return {
							label: field.name,
							value: fieldKey
						};
					}
					return null;
				}).filter(item => item !== null);
			}
            
            const getData = async () => {
                const res = await gettabledata({
					tablename: bgsx.value.tablename,
					cxtj: bgsx.value.cxtj,
					page: pagination.value.page,
					pageSize: pagination.value.size,
					search: search.value,
					filter: filterForm.value,
                    // 新增排序参数
                    sortField: sortParams.value.field,
                    sortOrder: sortParams.value.order,
                    sortType:  sortParams.value.sortType,
				});
				tableData.value = res.items;
				pagination.value.total = res.total;
			};
			
            // 分页事件处理
            const handlePageChange = (page) => {
                pagination.value.page = page;
                getData();
            }
            
            const handleSizeChange = (size) => {
                pagination.value.size = size;
                pagination.value.page = 1
                getData();
            }
            
            // 调用子组件新增数据
            const handleAdd = () => {
                tables.value.handleAdd();
            }
            
            //获取证书列字段
			const filterCertFields = () => {
				let zds = mapAndFilterFields(field => field.type === 'sczs');
				return zds[0]?.value || '';
			}
			
			// 生成证书
			const handleSczs = async () => {
				zdformData.storage_key = filterCertFields();
				if (!zdformData.id || !zdformData.name_field || !zdformData.storage_key) {
					return ElMessage.warning('请选择文件名列');
				}
				await sczsapi(zdformData);
				ElMessage.success('生成中，请耐心等待');
				showZSPopup.value = false;
			}
			
			// 生成Word
			const handleScword = async () => {
				wordformData.id = bgsx.value.id
				wordformData.field = mapAndFilterFields(field => field.type === 'word')[0]?.value
				if (!wordformData.id || !wordformData.field) {
					return ElMessage.warning('参数为空')
				}
				await scwordapi(wordformData);
				ElMessage.success('生成中，请耐心等待');
				showWordPopup.value = false;
			}
			
			// 选择行数据
			const SelectionChange = (rows) => {
			    selectrows.value = rows;
			    ids.value = rows.map(row => row.id);
			    zdformData.ids = ids.value;
			    wordformData.ids = ids.value;
			}
            
            // 清空数据
            const handleClean = async () => {
                try {
                    smartSpeak('确定清空数据吗')
                    await ElMessageBox.confirm(' 您确定清空全部数据吗？', '清空确认', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }); 
                    await qksjapi({ tablename: bgsx.value.tablename });
                    getData();
                } catch (error) {
                    if (error === 'cancel') {
                        return;  // 用户点击了取消，不进行处理
                    }
                    console.error(' 清空失败:', error);
                    ElMessage.error(' 清空失败，请稍后再试');
                    smartSpeak('清空失败')
                }
            }
            
            // 接收子组件的状态更新
            const handleDialogUpdate = (newValue) => {
                dialogBgsx.value = newValue;
            };
            
        	//高级筛选
        	const tablefilter = () => {
                if (filterzzf.value) {
                    filterForm.value = filterzzf.value.getfilterdata();
                    showFilterForm.value = false;
                    getData();
                } else {
                    console.error('子组件实例未找到');
                }
        	}
        	
            //重置高级筛选
        	const resttablefilter = () => {
                if (filterzzf.value) {
                    filterForm.value = {};
                    filterzzf.value.resttablefilter();
                    getData();
                } else {
                    console.error('子组件实例未找到');
                }
        	}
        	
             //批量查找，只支持一列
            const plczfunc = (e) => {
                if(!e) {
                    plcxdata.value = {key: '', value: ''};
                    filterForm.value = {};
                    getData();//恢复原来数据 
                }else if(plcxdata.value.key && plcxdata.value.value) {
                    const dataArray = plcxdata.value.value.split('\n').filter(row => row.trim() !== '').map(row => row.trim().split('\t'));
                    let newdata = {};
                    let newkey = plcxdata.value.key;
                    for(let v of dataArray){
                        newdata[newkey] ? newdata[newkey].push(v[0]) : newdata[newkey] = [v[0]];
                    }
                    filterForm.value[newkey] = {operator: 'in', value: JSON.stringify(newdata[newkey])};
                    getData();
                    plczdialog.value = false;
                }
            }
            
            //批量删除
            const plsc = async (type) => {
                if(type == 'all') {
                    handleClean();
                }else{
                    if(ids.value.length < 1) return ElMessage.error('请先选择要删除的数据');
                    try {
                        smartSpeak('确定删除吗')
                        await ElMessageBox.confirm(' 您确定要删除这条数据吗？', '删除确认', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }); 
                        await deltablerow({  id: bgsx.value.id,  ids: ids.value });
                        await getData();
                    } catch (error) {
                        if (error === 'cancel') {
                            return;  // 用户点击了取消，不进行处理
                        }
                        console.error(' 删除失败:', error);
                        ElMessage.error(' 删除失败，请稍后再试');
                        smartSpeak('删除失败')
                    }
                }
            }
            
        	//打印表格
        	const jsonPrint = async (i) => {
        	    if(Number(pagination.value.total) < 1 || selectrows.value?.length < 1) {
        	        return ElMessage.error('请先选择要打印的数据');
        	    }
        		if (printzzj.value && bgsx.value) {
        		    if(ids.value.length < 1) return ElMessage.error('请先选择要打印的数据');
                    printzzj.value.tablePrint(selectrows.value);
        		}
        	}
        	
            //批量查分
            const plcf = async () => {
                if (bgsx.value) {
                    try {
                        await ElMessageBox.confirm(
                            '点击页码可查看进度，不要重复点击查分', 
                            '请选择是否有验证码', 
                            {
                                type: 'success', 
                                confirmButtonText: '有验证码',
                                cancelButtonText: '无验证码',
                                distinguishCancelAndClose: true,
                            }
                        );
                        await plcfapi({ bm: bgsx.value.tablename, yzm: true });
                    } catch (error) {
                        if (error === 'cancel') {
                            await plcfapi({ bm: bgsx.value.tablename, yzm: false });
                            return;
                        }
                        ElMessage.error('操作失败，请稍后重试');
                        console.error(error);
                    }
                }
            }
            
            //批量发短信通知指定填报人有新项目，单次请求最多支持200个手机号且要求全为境内手机号或全为境外手机号
            const pldxfunc = async() => {
                if(bgsx.value.tablename) {
                    const res = await pldxapi({ids: ids.value, txt: bgsx.value.tablename});
                    ElMessage.success(res.message);
                    pldxdialog.value = false;
                }
            }
        	
            // 批量操作
            // filter_single_column：清晰地表示“单列筛选”操作。
            // batch_score_check：表示“批量查分”操作。
            // send_bulk_sms：表示“群发短信”操作。
            // print_selected_rows：表示“打印选择行”操作。
            // generate_certificate：表示“生成证书”操作。
            // generate_word：表示“生成Word”操作。
            // delete_selected_rows：表示“删除选择行”操作。
            // delete_all_rows：表示“删除全部”操作。
            const plcz = async (op) => {
                if (!op) return;
                const [action, type] = op.split('_') || [];
                if (action == 'filter') {
                    plczdialog.value = true;
                } else if (action == 'batch') {
                    plcf();
                } else if (action == 'send') {
                    pldxdialog.value = true;
                } else if (action == 'print') {
                    jsonPrint(type);
                } else if (action == 'generate') {
                    type == 'certificate' ? showZSPopup.value = true : showWordPopup.value = true;
                } else if (action == 'delete') {
                    plsc(type);
                }
            }
            
            // 排序
            const handleSortChange = (params) => {
                sortParams.value = {field: params.sortField, order: params.sortOrder, sortType: params.sortType};
                pagination.value.page = 1;
                getData();
            };
            
            return {
                id,
                ids,
                bgsx,
                filterzzf,
                tablefilter,
                resttablefilter,
                filterForm,
                showFilterForm,
                zdformData,
                mapAndFilterFields,
                processFieldOptions,
                tableData,
                getbgsx,
                getData,
                search,
                pagination,
                handlePageChange,
                handleSizeChange,
                columns,
                fields,
                jsonkeys,
                zdoptions,
                api,
                handleAdd,
                handleClean,
                tables,
                iszs,
                handleSczs,
                showZSPopup,
                isword,
                handleScword,
                showWordPopup,
                wordformData,
                filterCertFields,
                SelectionChange,
                dialogBgsx,
                handleDialogUpdate,
                gettbyuser,
                allusers,
                isadmin,
                plcz,
                plsc,
                plczdialog,
                plcxdata,
                filekey: ['file', 'multifile', 'word', 'image', 'multiimage', 'sczs'],
                plczfunc,
                jsonPrint,
                plcf,
                pldxfunc,
                activityType,
                zds,
                printzzj,
                selectrows,
                sortParams,
                handleSortChange
            };
        },
        
template: `
    <div style="margin-top: -20px;">
        <!-- 打印 -->
        <printexcel ref="printzzj" :zds="zds" :bgsx="bgsx" :allusers="allusers" :viewcolum="activityType" />
        <!-- 单列筛选 -->
        <el-dialog title="单列筛选 - 批量查找" v-model="plczdialog">
            <h3 style="color: red;margin: 0 0 15px 0;text-align:center;">选择查询列，然后从excel中复制要查找的列值，粘贴到下面的查询值里</h3>
                <el-form>
                    <el-form-item label="查询列">
                        <el-select v-model="plcxdata.key" placeholder="选择要批量查询的列" style="width:100%;">
                            <template v-for="(item, index) in bgsx.fields" :key="index">
                                <el-option :label="item.name" v-if="!filekey.includes(item.type)" :value="index"></el-option>
                            </template>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="查询值">
                    	<el-input v-model="plcxdata.value" autoHeight :rows="10" type="textarea" placeholder="粘贴到这" required></el-input>
                    </el-form-item>
                </el-form>
                <el-row justify="center">
                    <el-col :span="8" style="text-align: center;margin: 20px;">
                        <el-button type="primary" @click="plczfunc(true)">提交</el-button>
                        <el-button type="info" @click="plczfunc(false)">重置</el-button>
                        <el-button @click="plczdialog = false">取消</el-button>
                    </el-col>
                </el-row>
        </el-dialog>
		<!-- 生成证书弹窗 -->
		<el-dialog v-model="showZSPopup" title="批量生成证书" :before-close="() => showZSPopup = false">
		    <div style="color:red;margin:10px 40px;">可先在表格中选择指定行生成，不选则生成全部行。</div>
			<el-form :model="zdformData" label-width="120px">
				<el-form-item label="文件名列" prop="name_field" required>
					<el-select v-model="zdformData.name_field" placeholder="选择文件名列" clearable>
						<el-option v-for="item in zdoptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="覆盖生成" prop="overwrite">
					<el-switch v-model="zdformData.overwrite" active-text="是" inactive-text="否" />
				</el-form-item>
				<el-form-item label="被选择行">
                    {{ zdformData.ids.toString() }}
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showZSPopup = false">取消</el-button>
					<el-button type="primary" @click="handleSczs">确定</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 生成Word弹窗 -->
		<el-dialog v-model="showWordPopup" title="批量生成word" :before-close="() => showWordPopup = false">
		    <div style="color:red;margin:10px 40px;">可先在表格中选择指定行生成，不选则生成全部行。</div>
			<el-form :model="wordformData" label-width="120px">
				<el-form-item label="文件名列" prop="wjm" required>
					<el-select v-model="wordformData.wjm" placeholder="选择文件名列" clearable>
						<el-option v-for="item in zdoptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="覆盖生成" prop="overwrite">
					<el-switch v-model="wordformData.overwrite" active-value="是" inactive-value="否" />
				</el-form-item>
				<el-form-item label="被选择行">
                    {{ wordformData.ids.toString() }}
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showWordPopup = false">取消</el-button>
					<el-button type="primary" @click="handleScword">确定</el-button>
				</span>
			</template>
		</el-dialog>
		
		<!-- 追加导入 -->
        <el-dialog v-model="dialogBgsx" title="追加导入" width="85%">
            <zjdr :bgsx="bgsx" @update:dialog-visible="handleDialogUpdate" @update-success="getData"></zjdr>
    	</el-dialog>
    	
    	<!-- 高级筛选 -->
    	<el-dialog title="高级筛选" v-model="showFilterForm" width="61%">
            <filterform ref="filterzzf" :bgsx="bgsx" v-if="bgsx.tablename"></filterform>
            <el-row justify="center">
                <el-col :span="8" style="text-align: center;margin: 20px;">
                    <el-button type="primary" @click="tablefilter">确定</el-button>
                    <el-button type="info" @click="resttablefilter">重置</el-button>
                    <el-button @click="showFilterForm = false">关闭</el-button>
                </el-col>
            </el-row>
        </el-dialog>
		
        <div>
            <h3>{{bgsx.formname}}</h3>
        </div>
        <div style="display: flex; align-items: center;">
            <el-button type="primary" @click="handleAdd()">新增</el-button>
            <el-button type="primary" @click="dialogBgsx = true">追加导入</el-button>
            <exportxlsx :bgsx="bgsx" :ids="ids" :filterForm="filterForm" :columns="columns" :viewcolum="activityType" :total="pagination.total" v-if="isadmin" />
            <datafx :bgsx="bgsx" :total="pagination.total"/>
            <el-dropdown class="el-dropdown" @command="plcz" style="margin-left:10px;">
                <el-button type="primary">批量操作&nbsp;<el-icon><ArrowDown /></el-icon></el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="filter_single_column">单列筛选</el-dropdown-item>
                        <el-dropdown-item command="batch_score_check" v-if="isadmin">批量查分</el-dropdown-item>
                        <el-dropdown-item command="send_bulk_sms">群发短信</el-dropdown-item>
                        <el-dropdown-item divided command="print_selected_rows">打印选择行</el-dropdown-item>
                        <template v-if="isadmin">
                            <el-dropdown-item v-if="iszs" command="generate_certificate">生成证书</el-dropdown-item>
                            <el-dropdown-item v-if="isword" command="generate_word">生成word</el-dropdown-item>
                            
                            <el-dropdown-item divided command="delete_selected_rows" style="color:red;">删除选择行</el-dropdown-item>
                            <el-dropdown-item command="delete_all_rows" style="color:red;">删除全部</el-dropdown-item>
                        </template>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>

            <el-input style="width:500px;margin-left: 10px;" v-if="bgsx?.cxtj?.length" v-model="search" placeholder="输入关键词查找查询条件对应内容" clearable @keyup.enter="getData" @clear="getData">
                <template #prefix>
                	<el-icon class="el-input__icon"><search /></el-icon>
                </template>
				<template #append>
                    <el-button @click="getData">搜索</el-button>
                </template>
			</el-input>
            <el-button type="primary" @click="showFilterForm = true" style="margin-left:10px;">高级筛选</el-button>
            <el-icon :size="20" style="margin-left:20px;">
                <el-popover placement="bottom" trigger="hover" width="100">
                    <template #reference>
                        <el-button><Grid /></el-button>
                    </template>
                    <div style="overflow-y: auto">
                        <el-checkbox-group v-model="activityType">
                            <el-checkbox v-for="(item, key) in zds" :value="key" style="display: block">{{ item }}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-popover>
            </el-icon>
        </div>
        <div class="mt-1">
            <crudtable ref="tables" :key="bgsx.id" :data="tableData" :pagination="pagination" :columns="columns" :fields="fields" :bgsx="bgsx" :api="api"  :allusers="allusers" :viewcolum="activityType" @update-data="getData" @page-change="handlePageChange" @size-change="handleSizeChange" @selected-rows="SelectionChange" @sort-change="handleSortChange"/>
        </div>
    </div>
`
    }